
class MyLinkedList {
    constructor() {
        this.size = 0;
        this.head = null;
        this.last = null;
    }
    /**
     * 链表插入元素
     * @param index 插入位置
     * @param data 插入元素
    */
    insert (index, element) {
        if (index < 0 || index > this.size) {
            throw new Error("超出链表节点范围！");
        }
        let insertedNode = new Node(element);
        if (this.size === 0) {
            //空链表
            this.head = insertedNode
            this.last = insertedNode
        } else if (index === 0) {
            //插入头部
            insertedNode.next = this.head;
            this.head = insertedNode
        } else if (this.size === index) {
            //插入尾部
            this.last.next = insertedNode
            this.last = insertedNode;
        } else {
            //插入中间
            let prevNode = this.get(index - 1);
            insertedNode.next = prevNode.next;
            prevNode.next = insertedNode;
        }
        this.size++;
    }
    /**
     * 链表删除元素
     * @param index 删除的位置
     * */
    remove (index) {
        if (index < 0 || index > this.size) {
            throw new Error("超出链表节点范围！");
        }
        if (index === 0) {
            //删除头节点
            if (this.size === 1) {
                this.head = null
            } else {
                this.head = this.head.next
            }
        } else if (index === this.size - 1) {
            //删除尾节点
            let prevNode = this.get(index - 1);
            prevNode.next = null;
            this.last = prevNode;
        } else {
            let prevNode = this.get(index - 1);
            let nextNode = prevNode.next.next;
            prevNode.next = nextNode;
        }
        this.size--;
    }
    /**
     * 链表查找元素
     * @param index 查找的位置
     * */
    get (index) {
        if (index < 0 || index >= this.size) {
            throw new Error("超出链表节点范围！");
        }
        let temp = this.head
        for (let i = 0; i < index; i++) {
            temp = temp.next;
        }
        return temp
    }
    /**
     * 输出链表
     * */
    output () {
        let temp = this.head;
        while (temp !== null) {
            console.log(temp.element)
            temp = temp.next;
        }
    }
}
/**
 * 链表节点
 * */
class Node {
    constructor(element, next) {
        this.element = element;
        this.next = next || null;
    }
}

const myLinkedList = new MyLinkedList();

myLinkedList.insert(0, 3);
myLinkedList.insert(0, 4); //头插入
myLinkedList.insert(1, 6); //中间插入
myLinkedList.insert(2, 9); //中间插入
myLinkedList.insert(3, 5); //中间插入
myLinkedList.remove(0);
myLinkedList.output();

console.log(JSON.stringify(myLinkedList, 2))